package com.goodmr.passport.util;

import org.philcode.toolkit.core.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 网络工具包
 *
 * @author <a href="mailto:bingdong13@msn.com">bigo</a>
 */
public final class NetUtil {

    /**
     * 获取登录用户远程主机ip地址
     *
     * @return ip address
     */
    public static String getIpAddr() {

        HttpServletRequest request = httpServletRequest();

        return getIpAddr(request);
    }

    /**
     * 获取登录用户远程主机ip地址
     *
     * @param request http request
     * @return ip address
     */
    public static String getIpAddr(HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");

        if (isEmptyIp(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (isEmptyIp(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (isEmptyIp(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }

    /**
     * 获取 http servlet request
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest httpServletRequest() {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes.getRequest();
    }

    private static boolean isEmptyIp(String ip) {
        return StringUtils.isBlank(ip) ||
                "unknown".equalsIgnoreCase(ip);
    }
}
